package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * Listens for new clients.
 * On connection: Acquires a socket, creates new client and send it to clientHandler
 * @author Johannes
 *
 */
public class ConnectionListener implements Runnable{
	
	ServerSocket serverSocket;
	Thread thread;
	ClientFileCatalog catalog;
	
	/**
	 * Default constructor
	 * @param port port to listen on
	 * @param catalog catalog reference
	 * @throws IOException failed to start ServerSocket
	 */
	public ConnectionListener(int port, ClientFileCatalog catalog) throws IOException{
		this.catalog = catalog;
		serverSocket = new ServerSocket(port);
		thread = new Thread(this);
		thread.start();
	}

	/**
	 * 1. Listen for incoming calls from new clients 
	 * 2. Add them to client file catalog
	 */
	@Override
	public void run() {
		while(true){
			try {
				Socket clientSocket = serverSocket.accept();
				catalog.newClient(new Client(clientSocket, catalog));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
